<template>
  <div>
    <el-table :data="tableData" @row-dblclick="editRow" style="width: 100%">
      <el-table-column v-for="(column, index) in columns" :key="index" :label="column.label" :prop="column.prop">
        <template slot-scope="scope">
          <span v-if="!scope.row.editable">{{ scope.row[column.prop] }}</span>
          <el-input v-else v-model="scope.row[column.prop]" @blur="saveRow(scope.row)"></el-input>
        </template>
      </el-table-column>
    </el-table>
    <el-button @click="handleAdd" type="primary">新增一行</el-button>
    <el-button @click="handleSave" type="success">保存</el-button>
  </div>
</template>

<script>
export default {
  props: {
    columns: {
      type: Array,
      required: true
    },
    fetchData: {
      type: Function,
      required: true
    },
    saveData: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      tableData: []
    };
  },
  created() {
    this.fetchData().then(data => {
      this.tableData = data;
    });
  },
  methods: {
    handleAdd() {
      const newRow = {};
      this.columns.forEach(column => {
        newRow[column.prop] = '';
      });
      newRow.editable = true;
      this.tableData.push(newRow);
    },
    handleSave() {
      const dataToSave = this.tableData.filter(row => !this.isEmptyRow(row));
      dataToSave.forEach(row => {
        row.editable = false;
      });
      this.saveData(dataToSave);
    },
    editRow(row) {
      if (!row.editable) {
        this.tableData = this.tableData.map(item => {
          if (item === row) {
            return { ...item, editable: true };
          }
          return { ...item, editable: false };
        });
      }
    },
    saveRow(row) {
      row.editable = false;
    },
    isEmptyRow(row) {
      return this.columns.every(column => !row[column.prop]);
    }
  }
}
</script>
